var PATH_PREFIX ="";

function setPathPrefix(path){
	PATH_PREFIX =  path;
}
$(function() {
	// 给select2组件加载样式
	WASP_WIDGET.initializeSelectStyle();
	
	WASP_WIDGET.triggerInstSelect("#managerId");
	WASP_WIDGET.triggerSelectOnEmpId("#createId", {queryDimission : true,cleanDele: true});
	
	WASP_WIDGET.triggerDateRangeStyle("createTime");
	
	// 注册清空事件
    WASP_WIDGET.registerResetClearEvent();
    
    // 并默认显示第一个，并加载第一页
    NEWS_INFO.showMarketOpinion();
    
    NEWS_INFO.loadMarketOpinionData('1', 1, 'MarketOpinion');
    NEWS_INFO.loadMarketOpinionData('3', 1, 'AssetConfigAdvice');
    NEWS_INFO.loadMarketOpinionData('4', 1, 'SuperviseDynamicAnalyse');
});

var NEWS_INFO = {
	hideAddBtns: function() {
		$("#insertMarketOpinion").hide();
		$("#insertMarketHotPrj").hide();
		$("#insertAssetConfigAdvice").hide();
		$("#insertSuperviseDynamicAnalyse").hide();
		
		// 删除按钮
		$(".dmo").hide();
		$(".daca").hide();
		$(".dsda").hide();
	},
	
	hideAllTab: function() {
		this.hideAddBtns();
		
		$(".aca-search").hide();
		$(".sda-search").hide();
		$(".hot-search").hide();
		$(".mo-search").hide();
		
		$("#MarketOpinionGrid").hide();
		$("#MarketHotPrjGrid").hide();
		$("#AssetConfigAdviceGrid").hide();
		$("#SuperviseDynamicAnalyseGrid").hide();
		
		$("#market_opinion-search").hide();
		$("#market_hot_prj-search").hide();
		$("#asset_config_advice-search").hide();
		$("#supervise_dynamic_analyse-search").hide();
	},
	
	loadMarketOpinionData: function(newsType, pageNo, container) {
		var newsTitle = $.trim($("#newsTitle").val());   
	    var createId = $.trim($("#createId").val());  
	    var createTime0 = $("#createTime").getDateRangeValue()[0]; 
	    var createTime1 = $("#createTime").getDateRangeValue()[1]; 
	    
	    var postData = {
	    	limit: 20,
			pageNo: pageNo,
			'sp[newsType]': newsType,
			'sp[newsTitle]':newsTitle,
	        'sp[createId]':createId,
	        'sp[createTime0]':createTime0,
	        'sp[createTime1]':createTime1
	    }
		
		$.ajax({
			type : "POST",
			dataType : "json",
			url : PATH_PREFIX + 'newsInfoCommonListPage.do',
			cache: false,
			data: postData,
			success: function(data) {
				if (data.success) {
					// 初始化到页面上
					var $tpl = $('#newsTemplate').html();
					
					$.each(data.items, function(i, item) {
						var createTime = item.createTime;
						item.DD = moment(createTime).format('DD');
						item.YYYYMM = moment(createTime).format('YYYY-MM');
					});
					
					var view = {
						result: data.items
					}
					
					
				    $('#' + container + 'Grid .list-group').html(Mustache.render($tpl, view));
					
					// 重新初始化分页器
				    if (data.itemSize > 0) {
				    	$('#' + container + 'Paginator').show();
				    	$('#' + container + 'Paginator').bootstrapPaginator({
				    		currentPage: data.pageCount < pageNo ? data.pageCount : pageNo,
				    				totalPages: data.pageCount,
				    				size:"normal",
				    				bootstrapMajorVersion: 3,
				    				alignment:"right",
				    				numberOfPages:5,
				    				itemTexts: function (type, page, current) {
				    					switch (type) {
				    					case "first": return "首页";
				    					case "prev": return "上一页";
				    					case "next": return "下一页";
				    					case "last": return "末页";
				    					case "page": return page;
				    					}
				    				},
				    				onPageClicked: function (event, originalEvent, type, page){
				    					NEWS_INFO.loadMarketOpinionData(newsType, page, container);
				    				}
				    	});
				    } else {
				    	// 隐藏分页器
				    	$('#' + container + 'Paginator').hide();
				    }
				}
			}
		});
	
	},
	
	showMarketOpinion: function() {
		this.hideAllTab();
		
		$("#insertMarketOpinion").show();
		$(".dmo").show();
		$(".mo-search").show();
		$("#MarketOpinionGrid").show();
		$("#market_opinion-search").show();
	},
	showMarketHotPrj: function() {
		this.hideAllTab();
		
		$("#insertMarketHotPrj").show();
		$(".hot-search").show();
		$("#MarketHotPrjGrid").show();
		$("#market_hot_prj-search").show();
	},
	showAssetConfigAdvice: function() {
		this.hideAllTab();
		
		$("#insertAssetConfigAdvice").show();
		$(".daca").show();
		$(".aca-search").show();
		$("#AssetConfigAdviceGrid").show();
		$("#asset_config_advice-search").show();
	},
	showSuperviseDynamicAnalyse: function() {
		this.hideAllTab();
		
		$("#insertSuperviseDynamicAnalyse").show();
		$(".dsda").show();
		$(".sda-search").show();
		$("#SuperviseDynamicAnalyseGrid").show();
		$("#supervise_dynamic_analyse-search").show();
	},
	// 新增
	showInsertMarketOpinion: function() {
		var actionUrl = PATH_PREFIX + "commonNewsInfoAddView.do?newsType=1";
		window.open(actionUrl);
	},
	showInsertMarketHotPrj: function() {
		var actionUrl = PATH_PREFIX + "hotNewsInfoAddView.do";
		window.open(actionUrl);
	},
	showInsertAssetConfigAdvice: function() {
		var actionUrl = PATH_PREFIX + "commonNewsInfoAddView.do?newsType=3";
		window.open(actionUrl);
	},
	showInsertSuperviseDynamicAnalyse: function() {
		var actionUrl = PATH_PREFIX + "commonNewsInfoAddView.do?newsType=4";
		window.open(actionUrl);
	},
	// 详情
	showMarketOpinionDetail: function(id) {
		var actionUrl = PATH_PREFIX + "commonNewsInfoDetailView.do?id=" + id;
		window.open(actionUrl);
	},
	showMarketHotPrjDetail: function(id) {
		var actionUrl = PATH_PREFIX + "hotNewsInfoDetailView.do?id=" + id;
		window.open(actionUrl);
	},
	showAssetConfigAdviceDetail: function(id) {
		var actionUrl = PATH_PREFIX + "commonNewsInfoDetailView.do?id=" + id;
		window.open(actionUrl);
	},
	showSuperviseDynamicAnalyseDetail: function(id) {
		var actionUrl = PATH_PREFIX + "commonNewsInfoDetailView.do?id=" + id;
		window.open(actionUrl);
	},
	downloadMarketHotPrj: function(id) {
    	window.open(PATH_PREFIX + "downloadHotNews.do?id=" + id);
    },
    deleteCommonNews: function(id) {
    	ctools.confirm(
    		{title : "确认删除？", text: ""},
			function(isConfirm){
				if(isConfirm){
					$.ajax({
						type : "POST",
						dataType : "json",
						url : PATH_PREFIX + "deleteCommonNews.do",
						cache: false,
						data: {
							'id': id
						},
						success: function(data) {
							swal("删除成功", "", "success");
							queryByCondtion(false);
						},
						error:function(xhr){
						   sweetAlertAjaxError(xhr);
						}
					});
				}
			}
    	);
    }
};

var $newsInfoList_MarketHotPrj = $('#newsInfoList_MarketHotPrj');

var $gridparents = $("#myTabContent");//基于哪个父级元素使jqgrid自适应宽度，主要解决tab标签切换隐藏的列表宽度不对的问题
$(function() {
	// 市场热点产品
	$newsInfoList_MarketHotPrj.jqGrid({   
		url:PATH_PREFIX + 'newsInfoHotListPage.do',    
		//caption:'市场热点产品列表<button type="button" class="btn btn-default btn-sm btn-small btn-fullscreen" title="" tabindex="-1"><i class="fa fa-arrows-alt icon-fullscreen"></i></button>',  
		datatype: "json",
		colNames:["id", "产品名称","管理人","产品期限（月）","起投金额（元）","产品状态","风险等级","attCount","操作"],        
		colModel:[  { name: 'id', index: 'id', key: true, hidden:true },       
		            { name: 'prjName', index: 'prjName', width: 30, resizable: true, sortable: false },
		            { name: 'instSName', index: 'instSName', width: 30, resizable: true, sortable: false },
		            { name: 'prjTerm', index: 'prjTerm', width: 30, resizable: true, sortable: false },
		            { name: 'startInvestAmount', index: 'startInvestAmount', width: 30, resizable: true, sortable: false },
		            { name: 'prjStatusNm', index: 'prjStatusNm', width: 30, resizable: true, sortable: false },
		            { name: 'riskLevelNm', index: 'riskLevelNm', width: 30, resizable: true, sortable: false },
		            { name: 'attCount', index: 'attCount', hidden: true },
		            { name: 'option', index: 'option', width: 60, resizable: true, sortable: false }
				  ],
		rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        prmNames: { search: "search", page: "pageNo", rows: "limit" },
        height: 'auto',
        width: false,
        autowidth:true,
        editurl: '',
        viewrecords: true,
        cellEdit: false,
        shrinkToFit: true,
        grouping: false,
        jsonReader: {
            root: "items", //结果集
            records: "total", //总记录数 
            total: "pageCount", //总页数
            page: "pageNo", //当前页 
            repeatitems: false // (4) 
        },  
		multiselect:false,
		pager: "#newsInfoListPage_MarketHotPrj",						
		viewrecords: true,
		hidegrid: false, 
		gridComplete: function(){
			var ids = $newsInfoList_MarketHotPrj.jqGrid('getDataIDs');
			for(var i = 0;i < ids.length;i++){
				var rowId = ids[i];
				
				var rowData = $newsInfoList_MarketHotPrj.jqGrid('getRowData', rowId);
				var attCount = rowData.attCount;
			 
				var params = {
						'detail'   : 'detailMarketHotPrjTemp',
						'download' : 'downloadMarketHotPrjTemp'
					};
				var permissionButton = Permission_Button.configPermissionButton(params);
				permissionButton.detail   = Permission_Button.clickPermissionButton('detailMarketHotPrjTemp',"NEWS_INFO.showMarketHotPrjDetail('" + rowId + "');");
				if(attCount != 0) {
					permissionButton.download = Permission_Button.clickPermissionButton('downloadMarketHotPrjTemp',"NEWS_INFO.downloadMarketHotPrj('" + rowId + "');");
				}
				
				$newsInfoList_MarketHotPrj.jqGrid('setRowData', ids[i], { option: Permission_Button.linkAllBtn(permissionButton)});
			}	
		}
	});
	$newsInfoList_MarketHotPrj.navGrid('#newsInfoListPage_MarketHotPrj',{edit:false,add:false,del:false,search:false,refreshstate:'current'});
	$newsInfoList_MarketHotPrj.jqGrid('setFrozenColumns');
	jqGridResize($newsInfoList_MarketHotPrj, $gridparents);
});

//绑定回车事件,查询
$("body").keypress(function(event){
	var key = event.which;
	if(key == "13"){
		queryByCondtion(true);
	}
});

function queryByCondtion(flag, tab) {	
	if(tab) {
		if (tab == "market_opinion") {
			queryByCondtion_MO(flag);
		} else if(tab == "market_hot_prj") {
			queryByCondtion_MHP(flag);
		} else if (tab == "asset_config_advice") {
			queryByCondtion_ACA(flag);
		} else if (tab == "supervise_dynamic_analyse") {
			queryByCondtion_SDA(flag);
		}
	} else {
		var tabs = $("#myTabs li.active a");
		queryByCondtion(flag, tabs.attr("id").split("-")[0]);
	}
};

function queryByCondtion_MO(flag) {
	NEWS_INFO.loadMarketOpinionData('1', 1, 'MarketOpinion');
}

function queryByCondtion_MHP(flag) {
	queryByCondtionHot(flag, $newsInfoList_MarketHotPrj);
}

function queryByCondtion_ACA(flag) {
	NEWS_INFO.loadMarketOpinionData('3', 1, 'AssetConfigAdvice');
}

function queryByCondtion_SDA(flag) {
	NEWS_INFO.loadMarketOpinionData('4', 1, 'SuperviseDynamicAnalyse');
}

function queryByCondtionHot(flag, listDomObj) {
	var managerId = $.trim($("#managerId").val());   
    var prjName = $.trim($("#prjName").val());  
    var riskLevel = $.trim($("#riskLevel").val());  
    var prjStatus = $.trim($("#prjStatus").val());  
    
    var postData = listDomObj.jqGrid("getGridParam", "postData");
    $.extend(postData, {
        'sp[managerId]':managerId,
        'sp[prjName]':prjName,
        'sp[riskLevel]':riskLevel,
        'sp[prjStatus]':prjStatus
    });
    if (flag) {
    	listDomObj.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid", [{ page: 1 }]); //重新载入Grid表格
    } else {
    	listDomObj.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid"); //重新载入Grid表格
    }
}